<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

</body>
<script>
    let treeList = [
        {
            "title": "item-1",
            "children": [
                {
                    "title": "item-1-1",
                    "children": [
                        {
                            "title": "item-1-1-1",
                        },
                        {
                            "title": "item-1-1-1",
                        }
                    ]
                },
                {
                    "title": "item-1-2",
                }
            ]
        },
        {
            "title": "item-2",
            "children": [
                {
                    "title": "item-2-1",
                },
                {
                    "title": "item-2-2",
                }
            ]
        },
        {
            "title": "item-3",
            "children": [
                {
                    "title": "item-3-1",
                },
                {
                    "title": "item-3-2",
                }
            ]
        }
    ]
    console.log("treeList", treeList);


    function flatTree(treeList, pid = null) {
        let id = 1;
        function handleTree(treeList, pid = null) {
            treeList = JSON.parse(JSON.stringify(treeList));
            let tree = [];
            for (let i = 0; i < treeList.length; i++) {
                let item = treeList[i];
                if (!item.id) {
                    item.id = id++;
                }
                item.pid = pid;
                tree.push(item);
                if (item.children) {
                    let childTree = handleTree(item.children, item.id);
                    if (childTree.length) {
                        tree.push(...childTree);
                    }
                    delete item.children;// 在children中数据拉平之后, 删除children  (拉平后children不需要了)
                }
            }
            return tree;
        }

        return handleTree(treeList, pid = null)
    }

    console.log("flatTree", flatTree(treeList));

</script>

</html>